const pluginName = 'Js2HtmlWebpackPlugin';
const fs = require('fs');
const path = require('path');

const TEMPLATE_PATH = path.resolve(__dirname, '../temp.html');
const placeholder = new RegExp(/<!-- js2html -->/ig);

class Js2HtmlWebpackPlugin {
    constructor({
        scripts
    }) {
        this.scripts = scripts;
    }
    apply(compiler) {
        compiler.hooks.emit.tapAsync(pluginName, (compilation, callback) => {
            const assets = compilation.assets;

            if (this.scripts && this.scripts.length) {
                // 文件替换
                replace2Html(this.scripts);
            } else {
                let fileContent = '';

                Object.keys(assets).forEach((name) => {
                    // 获取源码
                    let source = assets[name].source();
                    fileContent += source;
                })
                createHtmlFile(fileContent);
            }

            callback()
        });
    }
}

/**
 * 创建文件
 * @param {string}} content 
 */
function createHtmlFile(content) {
    const _content = `<script>${content}</script>`;
    const _path = path.resolve(__dirname, '../dist/');
    let tempContent = readFile(TEMPLATE_PATH);
    // 替换占位符
    tempContent = tempContent.replace(placeholder, _content);

    // 打包路径检测
    const distPath = path.resolve(__dirname, '../dist/index.html');
    if (hasFile(distPath)) {
        removeFile(distPath);
    }

    // 生成最终html文件
    const writeStatus = writeFile(distPath, tempContent);
    if (writeStatus) {
        console.error(writeStatus);
    }
}

/**
 * 打包完成的js直接替换html占位符
 * @param {string[]} scripts js路径集合
 */
function replace2Html(scripts) {
    let tempContent = readFile(TEMPLATE_PATH);
    let sources = ``;
    // 读取文件内容
    for (let path of scripts) {
        const file = fs.readFileSync(path, 'utf-8');
        sources += `<script>${file}</script>`
    }
    // 替换占位符
    tempContent = tempContent.replace(placeholder, sources);

    // 打包路径检测
    const distPath = path.resolve(__dirname, '../dist/index.html');
    if (hasFile(distPath)) {
        removeFile(distPath);
    }

    // 生成最终html文件
    const writeStatus = writeFile(distPath, tempContent);
    if (writeStatus) {
        console.error(writeStatus);
    }
}


/**
 * 读取文件
 * @param {string} _path 文件路径
 * @returns {string}
 */
function readFile(_path) {
    return fs.readFileSync(_path, 'utf-8')
}

/**
 * 写入文件
 * @param {string} _path 文件路径
 * @param {string} content 写入内容
 * @returns 
 */
function writeFile(_path, content) {
    try {
        fs.writeFileSync(_path, content);
        return null;
    } catch (error) {
        return error;
    }
}

/**
 * 判断文件是否存在
 * @param {string} path 
 * @returns {boolean}
 */
function hasFile(_path) {
    return fs.existsSync(_path);
}

/**
 * 删除文件
 * @param {*} _path 
 * @returns {undefined}
 */
function removeFile(_path) {
    return fs.unlinkSync(_path);
}

module.exports = Js2HtmlWebpackPlugin;